//
//  Strore_TeHui_Controller.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/6.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "Strore_TeHui_Controller.h"
//untils
#import "UIColor+Hex.h"
#import "Global.h"
//views
#import "MenuScrollView.h"
#import "Strore_TeHui_Cell.h"
//controllers
#import "Strore_detailController.h"

#import "ManagerHttpBase.h"
#import "ManagerGlobeUntil.h"
#import "NSString+Conversion.h"

#import "XiaoQuAndStoreInfoModel.h"
//vendor
#import "MJRefresh.h"
#import "MTA.h"
@interface Strore_TeHui_Controller ()

//存储table视图
@property (nonatomic, strong)NSMutableArray *tableArr;
//数据源
@property (nonatomic, strong)NSMutableArray *dataSource;
@property (nonatomic, strong)NSMutableArray *recommendListDataSource;
@property (nonatomic, strong)NSMutableArray *limitListDataSource;
@property (nonatomic, strong)NSMutableArray *yiYuanBuyListDataSource;
//当前页
@property (nonatomic)NSInteger currentPage;
@property (nonatomic)NSInteger recommendListCurrentPage;
@property (nonatomic)NSInteger limitListCurrentPage;
@property (nonatomic)NSInteger yiYuanBuyCurrentPage;
//总条数
@property (nonatomic)NSInteger totalCount;
@property (nonatomic)NSInteger recommendListTotalCount;
@property (nonatomic)NSInteger limitListTotalCount;
@property (nonatomic)NSInteger yiYuanBuyTotalCount;
@end

@implementation Strore_TeHui_Controller
@synthesize dataSource = _dataSource;
@synthesize currentPage = _currentPage;
@synthesize totalCount = _totalCount;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"特惠专区";
    [self addBackNavItem];
    self.currentPage = 1;
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efeeee"];
    _tableArr = [[NSMutableArray alloc]init];
    [self setupSubView];
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self loadTeHuiDataWithType:[self tehuiIdWithTeHuiType:self.teHuiType] requestPage:self.currentPage requestCount:kRequestLimit];

    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[ManagerHttpBase sharedManager] managerReachability];
    if ([self.dataSource count] == 0) {
        if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
             [self loadTeHuiDataWithType:[self tehuiIdWithTeHuiType:self.teHuiType] requestPage:self.currentPage requestCount:kRequestLimit];
        }
       
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"特惠专区"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"特惠专区"];
}
#pragma mark -- 网络判断
- (void)networkIsOpen
{
    
}
- (void)networkIsClose
{
    
}

#pragma mark -- request Data
-(void)loadTeHuiDataWithType:(NSString*)type requestPage:(NSInteger)requestPage requestCount:(NSInteger)requestCount
{

//  请求参数说明：
//  CATEGORYCODE  类别代码    1：蔬菜水果，2：酒水饮料，3：生活百货，4：粮油调料，5：营养早餐
//  TYPE          优惠类型  1：普通，2：推荐，3：限量，4：一元购
//  PAGENUM		页码
//  PAGESIZE		数量
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                                inView:self.view];
    ManagerHttpBase *manager=[ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:type forKey:@"TYPE"];
    [parameter setObject:[NSNumber numberWithInteger:requestPage] forKey:@"PAGENUM"];
    [parameter setObject:[NSNumber numberWithInteger:requestCount] forKey:@"PAGESIZE"];
    [parameter setObject:[NSString stringISNull:mode.storeID] forKey:@"STOREID"];
//    [parameter setObject:@"1" forKey:@"STOREID"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"goods/list" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            
            if ([state isEqualToString:@"0"]) {//请求成功
                _totalCount = [[NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"TOTALROW"]] integerValue];
                if (weakSelf.currentPage == 1) {//请求第一页清空数据
                    [weakSelf.dataSource removeAllObjects];
                }
                NSMutableArray *dataArr = [[NSMutableArray alloc]init];
                [dataArr addObjectsFromArray:[weakSelf.dataSource copy]];
                [dataArr addObjectsFromArray:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"LIST"]];
                
                weakSelf.dataSource = dataArr;
                UITableView *tableView = (UITableView*)[weakSelf.tableArr objectAtIndex:weakSelf.teHuiType - 100];
                [tableView reloadData];
                
            } else {
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }

        }
        [weakSelf endRefresh];
    } failure:^(bool isFailure) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        [weakSelf endRefresh];
    }];

    
}
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     static NSString *CellIdentifier = @"TableViewCellIdentifier";
    
    Strore_TeHui_Cell *cell = (Strore_TeHui_Cell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[Strore_TeHui_Cell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        cell.backgroundColor = [UIColor whiteColor];
        cell.delegate = (id<Strore_TeHui_CellDelegate>)self;
        
    }
    //添加小图标
    if (tableView.tag==101) {//限量

        //cell.imageview.image=[self waterImageWithBgImageName:@"place_image" waterImageName:@"icon_limitcount" scale:[UIScreen mainScreen].scale];
    }else if(tableView.tag==102){//一元购

       // cell.imageview.image=[self waterImageWithBgImageName:@"place_image" waterImageName:@"icon_yiyuango" scale:[UIScreen mainScreen].scale];
    }
    
    cell.indexPath = indexPath;
    [cell updatawithData:[self.dataSource objectAtIndex:indexPath.row] withType:tableView.tag];
    return cell;

}


#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return HightScalar(130);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Strore_detailController *detailVC = [[Strore_detailController alloc]init];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dataDic = [self.dataSource objectAtIndex:indexPath.row];
    detailVC.goodsID = [NSString stringTransformObject:[dataDic objectForKey:@"ID"]];
    detailVC.isSelf = [NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]];
    [self.navigationController pushViewController:detailVC animated:YES];
}
#pragma mark -- MenuScrollViewDelegate
- (void)selectedMenuItemAtIndex:(NSInteger)index {
    
    if (index == 0) {
        self.teHuiType = krecommendType;
    } else if (index == 1) {
        self.teHuiType = klimitCountType;
    } else {
        self.teHuiType = kyiYuanGouType;
    }
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        self.currentPage = 1;
        [self loadTeHuiDataWithType:[self tehuiIdWithTeHuiType:self.teHuiType] requestPage:self.currentPage requestCount:klimitCountType];
    }
    
}

#pragma mark - 上拉/下拉  更新数据
-(void)headerRereshing {
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        self.currentPage = 1;
        [self loadTeHuiDataWithType:[self tehuiIdWithTeHuiType:self.teHuiType] requestPage:self.currentPage requestCount:klimitCountType];
    }else{
        [self endRefresh];
    }
    
}

-(void)footerRereshing
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        if (self.currentPage*kRequestLimit < self.totalCount) {
            self.currentPage++;
            [self loadTeHuiDataWithType:[self tehuiIdWithTeHuiType:self.teHuiType] requestPage:self.currentPage requestCount:klimitCountType];
        } else {
            [self endRefresh];
        }
    }else{
        [self endRefresh];
    }
}
- (void)endRefresh
{
    UITableView *tableView = (UITableView*)[self.tableArr objectAtIndex:self.teHuiType - 100];
    [tableView headerEndRefreshing];
    [tableView footerEndRefreshing];
}


#pragma mark -- Strore_TeHui_CellDelegate
-(void)gotoBuyWithItemTag:(NSInteger)tag {
    Strore_detailController *detailVC = [[Strore_detailController alloc]init];
    NSDictionary *dataDic = [self.dataSource objectAtIndex:tag];
    detailVC.goodsID = [NSString stringTransformObject:[dataDic objectForKey:@"ID"]];
    detailVC.isSelf = [NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]];
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark -- button Action
- (void)backBtnAction:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
#pragma mark -- setter and getter method
- (void)setTeHuiType:(TeHuiType)teHuiType {
    
    _teHuiType = teHuiType;
}
- (void)setDataSource:(NSMutableArray *)dataSource {
    switch (self.teHuiType) {
        case krecommendType:
            _recommendListDataSource = dataSource;
            break;
        case klimitCountType:
            _limitListDataSource = dataSource;
            break;
        case kyiYuanGouType:
            _yiYuanBuyListDataSource = dataSource;
            break;
            
        default:
            break;
    }
}

- (void)setCurrentPage:(NSInteger)currentPage {
    
    switch (self.teHuiType) {
        case krecommendType:
            _recommendListCurrentPage = currentPage;
            break;
        case klimitCountType:
            _limitListCurrentPage = currentPage;
            break;
        case kyiYuanGouType:
            _yiYuanBuyCurrentPage = currentPage;
            break;
            
        default:
            break;
    }

}

- (void)setTotalCount:(NSInteger)totalCount {
    switch (self.teHuiType) {
        case krecommendType:
            _recommendListTotalCount = totalCount;
            break;
        case klimitCountType:
            _limitListTotalCount = totalCount;
            break;
        case kyiYuanGouType:
            _yiYuanBuyTotalCount = totalCount;
            break;
            
        default:
            break;
    }

}

- (NSMutableArray*)dataSource {
    switch (self.teHuiType) {
        case krecommendType:
            return self.recommendListDataSource;
            break;
        case klimitCountType:
            return self.limitListDataSource;
            break;
        case kyiYuanGouType:
            return self.yiYuanBuyListDataSource;
            break;
        default:
            break;
    }
}

- (NSInteger)currentPage {
    switch (self.teHuiType) {
        case krecommendType:
            return self.recommendListCurrentPage;
            break;
        case klimitCountType:
            return self.limitListCurrentPage;
            break;
        case kyiYuanGouType:
            return self.yiYuanBuyCurrentPage;
            break;
        default:
            break;
    }
}

- (NSInteger)totalCount {
    switch (self.teHuiType) {
        case krecommendType:
            return self.recommendListTotalCount;
            break;
        case klimitCountType:
            return self.limitListTotalCount;
            break;
        case kyiYuanGouType:
            return self.yiYuanBuyTotalCount;
            break;
        default:
            break;
    }
}
#pragma mark -- 根据特惠类型标题返回特惠类型ID
- (NSString*)tehuiIdWithTeHuiType:(TeHuiType)tehuiType {
    
    if (tehuiType == krecommendType) {
        return @"2";
    } else if (tehuiType == klimitCountType) {
        return @"3";
    }else if (tehuiType == kyiYuanGouType) {
        return @"4";
    }
    return @"";
}
-(UIImage*)waterImageWithBgImageName:(NSString *)bgImageName waterImageName:(NSString *)waterImageName scale:(CGFloat)scale{
    // 生成一张有水印的图片，一定要获取UIImage对象 然后显示在imageView上
    
    //创建一背景图片
    UIImage *bgImage = [UIImage imageNamed:bgImageName];
    //NSLog(@"bgImage Size: %@",NSStringFromCGSize(bgImage.size));
    // 1.创建一个位图【图片】，开启位图上下文
    // size:位图大小
    // opaque: alpha通道 YES:不透明/ NO透明 使用NO,生成的更清析
    // scale 比例 设置0.0为屏幕的比例
    // scale 是用于获取生成图片大小 比如位图大小：20X20 / 生成一张图片：（20 *scale X 20 *scale)
    //NSLog(@"当前屏幕的比例 %f",[UIScreen mainScreen].scale);
    UIGraphicsBeginImageContextWithOptions(bgImage.size, NO, scale);
    
    // 2.画背景图
    [bgImage drawInRect:CGRectMake(0, 0, bgImage.size.width, bgImage.size.height)];
    
    // 3.画水印
    // 算水印的位置和大小
    // 一般会通过一个比例来缩小水印图片
    UIImage *waterImage = [UIImage imageNamed:waterImageName];
    CGFloat waterW = waterImage.size.width ;
    CGFloat waterH = waterImage.size.height;
    CGFloat waterX = 0;
    CGFloat waterY = 0;
    
    
    [waterImage drawInRect:CGRectMake(waterX, waterY, waterW, waterH)];
    
    // 4.从位图上下文获取 当前编辑的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    
    // 5.结束当前位置编辑
    UIGraphicsEndImageContext();
    
    
    return newImage;
}

#pragma mark -- setupSubView
- (void)setupSubView {
    NSArray *titles = @[@"推荐",@"限量",@"一元购"];
    //初始化scroll容器
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0
                                                                              , 44
                                                                              , self.view.frame.size.width
                                                                              , self.view.bounds.size.height - 49 - 64 -44 )];
    scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 3
                                        , self.view.bounds.size.height - 49 - 64 -44 );
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.bounces = NO;
    scrollView.pagingEnabled = YES;
    [self.view addSubview:scrollView];
    //初始化子视图
    for (NSInteger i = 0; i < [titles count]; i++) {
        CGRect frame = CGRectMake(i*CGRectGetWidth(scrollView.bounds)
                                  , 0, CGRectGetWidth(self.view.bounds)
                                  , CGRectGetHeight(scrollView.bounds));
        UITableView *tableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
        tableView.delegate = (id<UITableViewDelegate>)self;
        tableView.dataSource = (id<UITableViewDataSource>)self;
        //添加下拉刷新
        [tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
        //添加上拉加载更多
        [tableView addFooterWithTarget:self action:@selector(footerRereshing)];
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        tableView.tag = 100 + i;
        [scrollView addSubview:tableView];
        [self.tableArr addObject:tableView];
    }
    //初始化menuScrollView
    CGRect menuScrollViewFrame = CGRectMake(0, 0, self.view.bounds.size.width, 44);
    MenuScrollView *menu = [[MenuScrollView alloc]initWithFrame:menuScrollViewFrame titles:titles dataScrollView:scrollView];
    menu.backgroundColor = [UIColor grayColor];
    menu.selectIndex = self.selectedIndex;
    menu.showBottomLine = YES;
    menu.menuScrollDelegate = (id<MenuScrollViewDelegate>)self;
    menu.showVerticalLine = YES;
    menu.verticalLineImage = [UIImage imageNamed:@"vertical_sepLine_bg"];
    menu.bottomLineImage = [UIImage imageNamed:@"bottomLine_bg"];
    menu.tabBackgroundColor = [UIColor colorWithHexString:@"#dddddd"];
    menu.tabSelectedBackgroundColor = [UIColor colorWithHexString:@"#fffff"];
    menu.tabSelectedTitleColor  = [UIColor colorWithHexString:@"#c52720"];
    menu.tabTitleColor = [UIColor colorWithHexString:@"#555555"];
    [self.view addSubview:menu];
    
}


@end
